# -*- encoding=utf8 -*-

__author__ = "code哥"
import subprocess
import os
from sanic.blueprints import Blueprint
from sanic.views import HTTPMethodView
from sanic import response
from sanic_openapi import doc

blueprint = Blueprint(__name__, '/api')


class RYMStart(HTTPMethodView):

    @doc.summary("重启媷羊毛单个脚本程序")
    @doc.consumes({"view": {"script": str, "device": str}}, location="body")
    def post(self, request):
        script = request.json.get('script', '')
        device = request.json.get('device', '')
        # 先kill之前的
        kill_command = "ps -ef | grep %s.py | grep %s | grep -v grep | awk '{print $2}' | xargs kill -TERM" \
                       % (script, device,)
        kill_process = subprocess.Popen(kill_command,
                                        shell=True, close_fds=True, stdin=subprocess.PIPE,
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE)
        kill_process.wait()
        command = 'nohup python3 -u {path}/src/{script}.py {parms} >> {path}/run.log 2>&1 &'.format(
            path=os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
            script=script,
            parms=device,
        )
        process = subprocess.Popen(command,
                                   shell=True, close_fds=True, stdin=subprocess.PIPE,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        process.wait()
        return response.json({'code': 0, 'data': {'msg': '重启成功'}})


blueprint.add_route(RYMStart.as_view(), '/rym_single_restart', strict_slashes=True)
